//
//  selectFoodfenshuViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/7/5.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "selectFoodfenshuViewController.h"
#import "foodJiluViewController.h"

@interface selectFoodfenshuViewController ()<UITextFieldDelegate,UIScrollViewDelegate>
@property (nonatomic,weak)UIScrollView *scrollView;

@property (nonatomic,weak)UIImageView *foodImage;
@property (nonatomic,weak)UILabel *foodName;
@property (nonatomic,weak)UILabel *huanSuanLabel;
@property (nonatomic,weak)UITextField *countTextField;

@property (nonatomic,weak)UIButton *firstButton;
@property (nonatomic,strong)UIButton *starButton;

@property (nonatomic,weak)UIButton *foodTimeButton;
@property (nonatomic,strong)UIButton *starButton1;


@property (nonatomic,assign)CGFloat y;

@property (nonatomic,strong)NSArray *yingyangArray;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,assign)CGFloat oneWeight; //一份食物多少克


@end

@implementation selectFoodfenshuViewController

-(NSArray *)dataArray
{
    if(!_dataArray)
    {
        _dataArray = [NSMutableArray array];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f千卡",[self weightChange:self.selectFood.calori]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f克",[self weightChange:self.selectFood.water]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f克",[self weightChange:self.selectFood.protein]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f克",[self weightChange:self.selectFood.fat]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f克",[self weightChange:self.selectFood.df]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f克",[self weightChange:self.selectFood.carbohydrate]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f毫克",[self weightChange:self.selectFood.va]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f毫克",[self weightChange:self.selectFood.vb1]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f毫克",[self weightChange:self.selectFood.vb2]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f毫克",[self weightChange:self.selectFood.vc]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f毫克",[self weightChange:self.selectFood.ve]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f毫克",[self weightChange:self.selectFood.niacin]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f毫克",[self weightChange:self.selectFood.na]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f毫克",[self weightChange:self.selectFood.ca]]];
         [_dataArray addObject:[NSString stringWithFormat:@"%.1f毫克",[self weightChange:self.selectFood.fe]]];
    }
    return _dataArray;
}

//元素重量转换
-(CGFloat)weightChange:(NSString *)str
{
    
    CGFloat bizhi = [self.selectFood.calori floatValue] / 90.0;
    
    CGFloat weight = 0;
    CGFloat calori = [str floatValue];
    weight = calori / bizhi;
    return weight;
}



-(NSArray *)yingyangArray
{
    if(!_yingyangArray)
    {
        _yingyangArray = @[@"热量",@"水分",@"蛋白质",@"脂肪",@"膳食纤维",@"碳水化合物",@"维生素A",@"维生素B1",@"维生素B2",@"维生素C",@"维生素E",@"烟酸",@"钠",@"钙",@"铁"];
    }
    return _yingyangArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = YMColor(245, 245, 245);
    self.title = @"食物详情";
    //设置右按钮
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame =  CGRectMake(0, 0, 50.0f, 30.0f);
    [addButton setTitle:@"添加" forState:normal];
    [addButton setTitleColor:YMColor(255, 218, 245) forState:UIControlStateNormal];
    UIBarButtonItem *addButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    self.navigationItem.rightBarButtonItem = addButtonItem;
    [addButton addTarget:self action:@selector(addFood) forControlEvents:UIControlEventTouchUpInside];
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight )];
    self.scrollView = scrollView;
    scrollView.delegate = self;
    scrollView.bounces = NO;
    [self.view addSubview:scrollView];
    
    [self imageAndTitleLayout];
    [self selectFenCountAddToView];
    [self yingyangIntroducelayout];
}

//点击空白处收缩键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.countTextField resignFirstResponder];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    [self.countTextField resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    YMLog(@"开始了");
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    YMLog(@"结束了  %f",self.oneWeight);
    
}

/**添加按钮*/
-(void)addFood
{
 
    if(![self.countTextField.text isEqualToString:@""])
    {
        [self postAddFoodInformationToServices];
    }
    else
    {
        [MBProgressHUD showError:@"请输入食物克数！"];
    }
    
}

//上传添加食物的信息
-(void)postAddFoodInformationToServices
{
    [MBProgressHUD showMessage:@"正在添加食物，请稍后..."];
    CGFloat totalCount = [self.countTextField.text floatValue];
    NSString *urlString = @"http://120.24.178.16:8080/Health/food/saveUserFoodRecord.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"Account=%@&foodId=%@&orderId=%@&weight=%@&foodnumber=%@&nowtime=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"],self.selectFood.foodID,[NSString stringWithFormat:@"%lu",self.btnTag],[NSString stringWithFormat:@"%.1f",totalCount],[NSString stringWithFormat:@"%.1f",totalCount / self.oneWeight],self.selectDateString];
    YMLog(@"str = %@",str);
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            YMLog(@"dict = %@",dict);
            if([[dict objectForKey:@"code"]isEqualToString:@"0"])
            {
                [MBProgressHUD showSuccess:@"添加成功!"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
//                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2]animated:YES];
                    [[NSUserDefaults standardUserDefaults]setObject:@"haveChanged" forKey:@"changed"];
                });
            }
            else
            {
                [MBProgressHUD showError:[dict objectForKey:@"message"]];
            }
        }
    }];
}

/**图片和名字布局*/
-(void)imageAndTitleLayout
{
    self.y = 8.0f;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, self.y, kDeviceWidth, 80)];
    view.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:view];
    
    self.y += view.frame.size.height;
    [self setLineStartX:0 andStartY:self.y andWidth:kDeviceWidth andHeight:1.0f ToView:self.scrollView];
    self.y += 1.0f;
    
    
    UIImageView *foodImage = [[UIImageView alloc]initWithFrame:CGRectMake(20, 15, 50, 50)];
    NSURL *url = [[NSURL alloc]initWithString:self.selectFood.imgSrc];
    [foodImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zonghe"]];
    [view addSubview:foodImage];
    self.foodImage = foodImage;
    
    
    CGFloat w = view.frame.size.width;
    
    UILabel *nameLable = [[UILabel alloc]initWithFrame:CGRectMake(w / 4.0, 8, w / 2.0, 40)];
    nameLable.textColor = YMColor(189, 79, 136);
    nameLable.text = [NSString stringWithFormat:@"%@",self.selectFood.name];
    self.foodName = nameLable;
    [view addSubview:nameLable];
    
    UILabel *huansuanLabel = [[UILabel alloc]initWithFrame:CGRectMake(w / 4.0, 32, w, 40)];
    
    self.oneWeight = (([self.selectFood.comestible floatValue] * 90) / [self.selectFood.calori floatValue]);
    
    huansuanLabel.text = [NSString stringWithFormat:@"1份%@ = %.1f克 ＝ 90千卡",self.selectFood.name,self.oneWeight];
    huansuanLabel.textColor = YMColor(114, 114, 114);
    self.huanSuanLabel = huansuanLabel;
    [view addSubview:huansuanLabel];
}

/**选择份量布局*/
-(void)selectFenCountAddToView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, self.y, kDeviceWidth, 60)];
    view.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:view];
    self.y += view.frame.size.height;
    [self setLineStartX:0 andStartY:self.y andWidth:kDeviceWidth andHeight:1.0f ToView:self.scrollView];
    self.y += 1.0f;
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 100, 40)];
    label1.textColor = YMColor(197, 109, 152);
    label1.text = @"选择份量:";
    [view addSubview:label1];
    
    CGFloat w = view.frame.size.width;
    UITextField *countTextField = [[UITextField alloc]initWithFrame:CGRectMake(w / 4.0 , 10, w / 2.0, 40)];
    countTextField.placeholder = @"请输入食物克数";
    countTextField.font = [UIFont systemFontOfSize:15.0f];
    countTextField.textColor = YMColor(114, 114, 114);
    countTextField.delegate = self;
    countTextField.tag = 1;
    countTextField.keyboardType = UIKeyboardTypeDecimalPad;
    countTextField.textAlignment = NSTextAlignmentCenter;
    self.countTextField = countTextField;
    [view addSubview:countTextField];
    self.countTextField.text = [NSString stringWithFormat:@"%.1f",self.oneWeight];
    
    UILabel *danweiLabel = [[UILabel alloc]initWithFrame:CGRectMake(w / 4.0 * 3 + 20, 10, 50, 40)];
    danweiLabel.textColor = YMColor(114, 114, 114);
    danweiLabel.text = @"克";
    [view addSubview:danweiLabel];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(infoTextField) name:UITextFieldTextDidChangeNotification object:nil];
}

-(void)infoTextField
{
    CGFloat weight = [self.countTextField.text floatValue];
    if(weight > 0)
    {
        self.huanSuanLabel.text = [NSString stringWithFormat:@"%.1f份%@ = %.1f克 ＝ %.1f千卡",weight / self.oneWeight,self.selectFood.name,weight,weight / self.oneWeight * 90];
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

/**营养元素布局*/
-(void)yingyangIntroducelayout
{
    self.y += 5.0f;
    [self setLineStartX:0 andStartY:self.y andWidth:kDeviceWidth andHeight:1 ToView:self.scrollView];
    self.y += 1.0f;
    
    UILabel *yingyangTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.y, kDeviceWidth / 2.0, 50)];
    yingyangTitleLabel.textAlignment = NSTextAlignmentCenter;
    yingyangTitleLabel.textColor = YMColor(191, 79, 140);
    yingyangTitleLabel.text = @"营养元素";
    yingyangTitleLabel.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:yingyangTitleLabel];
    
    UILabel *countLabel = [[UILabel alloc]initWithFrame:CGRectMake(kDeviceWidth / 2.0, self.y, kDeviceWidth / 2.0, 50)];
    countLabel.textAlignment = NSTextAlignmentCenter;
    countLabel.textColor = YMColor(191, 79, 140);
    countLabel.text = @"每1份";
    [self.scrollView addSubview:countLabel];
    countLabel.backgroundColor = [UIColor whiteColor];
    [self setLineStartX:kDeviceWidth / 2.0 andStartY:self.y andWidth:1 andHeight:500 ToView:self.scrollView];
    self.y += 50.0f;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, self.y, kDeviceWidth / 2.0, 450)];
    [self.scrollView addSubview:leftView];
    
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(kDeviceWidth / 2.0, self.y, kDeviceWidth / 2.0, 450)];
    [self.scrollView addSubview:rightView];
    
    [self setLineStartX:kDeviceWidth / 2.0 andStartY:self.y andWidth:1 andHeight:450 ToView:self.scrollView];
    self.y += leftView.frame.size.height;
    [self setLineStartX:0 andStartY:self.y andWidth:kDeviceWidth andHeight:1 ToView:self.scrollView];
    self.scrollView.contentSize = CGSizeMake(kDeviceWidth, self.y + 10.0);
    
    [self addLabelAndLineToView:leftView andArray:self.yingyangArray];
    [self addLabelAndLineToView:rightView andArray:self.dataArray];
    
}

-(void)addLabelAndLineToView:(UIView *)view andArray:(NSArray *)array
{
    CGFloat w = view.frame.size.width;
    CGFloat h = view.frame.size.height;
    
    for(int i = 0;i < 15;i ++)
    {
        CGFloat w1 = w;
        CGFloat h1 = h / 15.0;
        CGFloat x = 0;
        CGFloat y = h1 * i;
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(x, y, w1, h1)];
        label.textColor = YMColor(114, 114, 114);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = array[i];
        label.font = [UIFont systemFontOfSize:15.0f];
        [view addSubview:label];
        
        [self setLineStartX:0 andStartY:y andWidth:w andHeight:1 ToView:view];
    }
}


/**横线和竖线*/
-(void)setLineStartX:(CGFloat)x andStartY:(CGFloat)y andWidth:(CGFloat)w andHeight:(CGFloat)h ToView:(UIView *)view
{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(x, y, w, h)];
    label.backgroundColor = YMColor(218, 218, 218);
    [view addSubview:label];
}

//获取系统时间
-(NSString *)getSystemTime
{
    NSDate *senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}



@end
